import base64
import hashlib

import bcrypt

from ...db import models as db
from ...db.util import transaction
from ...exceptions import MissingParameterError, \
                          MobileDuplicatedError
from ..base import BaseProcessor




class ImageProcessor(BaseProcessor):
    """用户基本资料/users

    """
    @transaction()
    def create(self, *args, **kwargs):
        """Param

        args:( None )
        kwargs:{ ... }
        """
        # Required

        if 'author' not in kwargs:
            raise MissingParameterError('author is missing')

        if 'width' not in kwargs:
            raise MissingParameterError('width is missing')

        if 'height' not in kwargs:
            raise MissingParameterError('height is missing')

        if 'size' not in kwargs:
            raise MissingParameterError('size is missing')

        if 'path' not in kwargs:
            raise MissingParameterError('path is missing')

        if 'url' not in kwargs:
            raise MissingParameterError('size is missing')


        obj = db.Image(**kwargs)
        self.dbh.add(obj)

        return obj

    @transaction()
    def read(self, *args, **kwargs):
        return self.query(*args, **kwargs)

    def query(self, *args, **kwargs):
        """Param

        args:( imageid )
        kwargs:{ imageid, }
        """
        # 结果集
        document = kwargs.pop('document', False)
        collection = kwargs.pop('collection', False)

        # 查询参数
        params = kwargs.pop('params', {})

        q = self.dbh.query(db.Image)

        if args:
            try:
                imageID = args[0]
                q = q.filter_by(id=imageID)
            except IndexError:
                pass
            if collection is True:
                return q.all()
            return q.first()

        if kwargs:
            q = q.filter_by(**kwargs)
            if document is True:
                return q.first()
            return q.all()

        if document is True:
            return q.first()
        return q.all()  # collection/True

    @transaction()
    def update(self, *args, **kwargs):
        """Param

        args:( imageID )
        kwargs:{ ... }
        """
        if not args or not kwargs:
            raise MissingParameterError()
            return False


        imageID = args[0]

        # TODO HERE

        self.dbh.query(db.Image)\
                .filter_by(imageid=imageID)\
                .update(kwargs)

        return self.query(*args)
